Secret Recipes of the Python Ninja by Cody Jackson

Secret Recipes of the Python Ninja by Cody Jackson

Author:Cody Jackson
Language: eng
Format: epub
Publisher: Packt Publishing
Published: 2018-05-21T08:59:52+00:00


How to do it...

The following examples are taken from the Python documentation at https://docs.python.org/3/library/collections.html#collections.defaultdict:

A list is a common source for default_factory, as it makes it easy to group a sequence of key:value pairs into a dictionary of lists, as follows:

>>> from collections import defaultdict

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

>>> d = defaultdict(list)

>>> for k, v in s:

... d[k].append(v)

...

>>> sorted(d.items())

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

First, a list of tuples is created. The tuples match a string with an integer.

A defaultdict is created using an empty list as the factory argument.

The list of tuples is iterated through, assigning the tuple key:value pairs to the defaultdict list's factory.

When the sorted dictionary is printed, it shows that the defaultdict created a new key for each new item from the tuple's list. If a key was already present in the dictionary, then the tuple's value was added to the key's value as a new item in a list via the append function. Basically, the tuple's list was shorted to a key:value pairing that identified all the values related to a particular key.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.